﻿using Dyao.Repository.Abstractions;
using Dyao.Book.Contract;
using Dyao.Book.Core;
using Foundation.Core;
using Foundation.Uow;
using Microsoft.Extensions.DependencyInjection;

namespace Dyao.Book.Application
{
    /// <summary>
    /// 验证当前用户是否有相同的任务在运行
    /// </summary>
    [TaskCenterRuleName(RuleKey, DisplayName = "验证当前用户是否有相同的任务在运行")]
    public class UserSameTaskRunningTaskRuleExecutor : TaskRuleExcutorBase, ITaskRuleExcutor, ITransientDependency
    {
        public const string RuleKey = TaskCenterRuleExcutorKeyInfo.UserSameTaskRunnning;
        public override string Key => RuleKey;

        public async override Task ExcuteAsync(TaskCenterRuleExcutingContext context)
        {
            var userId = ServiceProvider.GetService<ICurrentUser>().GetUserId().ToInt();
            var recordRepository = ServiceProvider.GetService<ITaskCenterRecordRepository>();

            using var unitOfWork = ServiceProvider.GetService<IUnitOfWorkManager>().Begin(true,true);
            var hasSameTaskRunning = await recordRepository
                .IsExistAsync(t => t.CreateUserId == userId
                    && (t.Status == TaskCenterRecordStatusEnum.Pending || t.Status == TaskCenterRecordStatusEnum.Excuting)
                    && t.TaskCenterSettingsId == context.TaskCode);

            if (hasSameTaskRunning)
            {
                throw new BusinessException("TaskRule.UserSameTaskRunning", "您存在相同的任务正在执行，请任务执行结束后重试！");
            }
        }
    }
}
